// Copyright (c) 2023 Presto Labs Pte. Ltd.
// Author: qiang

#include "coin2/exchange/mercado/api_util/rate_tracker.h"

namespace coin2::exchange::mercado::api_util {

constexpr auto EXAMPLE_SPOT_BYBIT = R"(
"connection_config": {
  "key_filepath": "/home/ec2-user/config/trade/xunke18/mercado/trade_key.json",
  "rate_limit_info": {
    "spot_mercado": {
      "req_all": {
        "secs": 60,
        "reqs": 2000
      }
    }
  }
},)";

template <class RateTracker>
void CheckFail(RateTracker&& rate_tracker, bool check_result) {
  if (!check_result) {
    LOG(INFO) << "Hit rate limit on [" << rate_tracker->GetName() << "]";
  }
}

MercadoRateTracker::MercadoRateTracker(const MarketExchangeApi& mea,
    const coin2::exchange::order::OrderConnectionConfig& cfg) {
  if (mea.market == coin::proto::MarketType::Spot) {
    RateLimitInfoSpotMercado rate_config;
    RateConfig::Get()->GetConfig(mea, cfg, &rate_config);
    InitRateTracker(&rate_config, mea.String(), EXAMPLE_SPOT_BYBIT);
  } else {
    CHECK(false) << "unsupported mea: " << mea.String();
  }
}

void MercadoRateTracker::InitRateTracker(
    RateLimitInfoSpotMercado* rate_config,
    std::string_view mea_str,
    std::string_view example) {
  if (!rate_config || !rate_config->has_req_all()) {
    coin2::exchange::base::order::RateConfig::CheckFail(mea_str, example);
  }

  const auto& req_all = rate_config->req_all();
  LOG(INFO) << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
      << "\nOG request rate was set as below:\n"
      << "\nreq_all: [" << req_all.reqs() << "(reqs)/" << req_all.secs() << "(secs)]"
      << "\n\nOr you can configure customized rate in driver config. For example: " << example
      << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";

  rate_tracker_req_all_ = 
      std::make_unique<FixedWindowRateTracker>(req_all.secs() * 1'000'000'000LL);
  rate_tracker_req_all_->SetRateLimitInfo(req_all.reqs(), req_all.reqs());
  rate_tracker_req_all_->SetName("mercado_rate_tracker_method");

  rate_limit_report_writer_ = std::make_unique<RateLimitReportWriter>();
  rate_limit_report_writer_->SetRateLimitInfoString(rate_config);
}

bool MercadoRateTracker::HasEnoughRateLimit(int64_t timestamp, ActionType action_type) {
  bool ret = true;
  if (rate_tracker_req_all_) {
    ret = rate_tracker_req_all_->GetRemaining(timestamp) > 2;
    CheckFail(rate_tracker_req_all_, ret);
  }

  if (!ret) {
    rate_limit_report_writer_->SetHitRateLimit(timestamp, action_type);
  }
  return ret;
}

void MercadoRateTracker::Push(int32_t num_reqs, int64_t timestamp, ActionType action_type) {
  if (action_type == ActionType::QUERY) {
    if (rate_tracker_req_all_) {
      rate_tracker_req_all_->Push(num_reqs, timestamp);
    }
  } else {
    return;
  }
}

void MercadoRateTracker::SetRateLimitInfoString(const google::protobuf::Message* message) {
  if (!rate_limit_report_writer_) {
    return;
  }
  rate_limit_report_writer_->SetRateLimitInfoString(message);
}

void MercadoRateTracker::WriteRateLimitReportMessage(OrderLoggerCB callback) {
  if (!callback) {
    return;
  }
  rate_limit_report_writer_->Write(callback);
}

double MercadoRateTracker::GetMaxRateUsedRatio(int64_t timestamp, ActionType action_type) {
  switch (action_type) {
    case ActionType::PLACE: {
      return GetMaxRateUsedRatio(rate_tracker_req_all_, timestamp);
    }
    case ActionType::CANCEL: {
      return GetMaxRateUsedRatio(rate_tracker_req_all_, timestamp);
    }
    case ActionType::QUERY: {
      return GetMaxRateUsedRatio(rate_tracker_req_all_, timestamp);
    }
    case ActionType::AMEND: {
      return GetMaxRateUsedRatio(rate_tracker_req_all_, timestamp);
    }
    default: {
      // shouldn't reached here
      LOG(ERROR) << "ops~ something is wrong, action_type=" << action_type;
      return 0.;
    }
  }
}

}  // namespace coin2::exchange::mercado::api_util
